<?
global $g_precision,$g_bess_user,$g_log_rate,$g_pulse_rate;

$box  = array();
$conf = array();

$nameMonth[1]  = 'januari';
$nameMonth[2]  = 'februari';
$nameMonth[3]  = 'mars';
$nameMonth[4]  = 'april';
$nameMonth[5]  = 'maj';
$nameMonth[6]  = 'juni';
$nameMonth[7]  = 'juli';
$nameMonth[8]  = 'augusti';
$nameMonth[9]  = 'september';
$nameMonth[10] = 'oktober';
$nameMonth[11] = 'november';
$nameMonth[12] = 'december';

// Month size

$limMonth[1]  = 31;
$limMonth[2]  = 28;
$limMonth[3]  = 31;
$limMonth[4]  = 30;
$limMonth[5]  = 31;
$limMonth[6]  = 30;
$limMonth[7]  = 31;
$limMonth[8]  = 31;
$limMonth[9]  = 30;
$limMonth[10] = 31;
$limMonth[11] = 30;
$limMonth[12] = 31;

// Skottår
$limYear[2016][2] = 1;
$limYear[2020][2] = 1;
$limYear[2024][2] = 1;
$limYear[2028][2] = 1;

//============================
function getFileName($pre,$year,$month,$day,$ext)
{
  $fil = "data/$pre-$year";
  //echo("x1 $fil  ($pre)<br>");

  if($pre == 'month') $fil = $fil."-$month";
  else
    $fil = $fil."-$month-$day";

  //echo("x2 $fil<br>");
  $fil = $fil.".$ext";
  //echo("getFileName $fil<br>");
  return($fil);
}
//============================
function readConf() 
{
   global $g_bess_user,$g_log_rate,$g_pulse_rate;
   $in  = fopen("bess.conf","r");
   if($in)
   {
      while (!feof($in))
        {
          $row  = fgets($in);
          sscanf($row,"%s %s",$key,$value);
          if($key=='BESS_USER') $g_bess_user   = $value;
          if($key=='PULSE_RATE')$g_pulse_rate  = $value;
          if($key=='LOG_RATE')  $g_log_rate    = $value;
          if($key=='PRECISION') $g_precision   = $value;
        }
       fclose($in);
    }
}
//============================
function readFileSum($file)
{
   global $g_pulse_rate;
   $value = "0\n";
   $in  = fopen($file,"r");
   if($in)
   {
       $row  = fgets($in);
       $data = explode(",", $row);
       $value = $data[0];
   }
   //else
   // echo("ERROR (readFileSum) unable to open $file<br>");
   //echo("1 $file $value<br>");
   $value=trim($value);
   $value = $value/$g_pulse_rate;
   //echo("2 $file $value<br>");
   return($value);
}
//============================
function readFileMax($file)
{
   $value = "0\n";
   $in  = fopen($file,"r");
   if($in)
   {
       $row  = fgets($in);
       $data = explode(",", $row);
       $value = $data[1];
   }
   //else
   // echo("ERROR (readFileMax) unable to open $file<br>");
   //echo("$file $value<br>");
   return($value);
}
//============================
function writeFile($file,$value,$maxValue) 
{
     $out = fopen($file,"w");
     if($out)
     {
       $content =$value.','.$maxValue."\n";
       fwrite($out,$content,strlen($content)); 
       fclose($out); 
     }
     else
      echo("ERROR (writeFile): unable to open $file<br>");
}
//============================
function lessDataFiles($year,$month,$day) 
{
  $data = array();
  $filename1 = getFileName('hour',$year,$month,$day,'less');
  $filename2 = getFileName('day',$year,$month,$day,'close');
  if (file_exists($filename1) && file_exists($filename2)) return;

   $dataFile = getFileName('bess',$year,$month,$day,'txt');

   $in  = fopen($dataFile,"r");
   if($in)
   {
	  echo("Condense Primary Data: $year-$month-$day<br>");
      while (!feof($in))
      {
          $row   = fgets($in);
          $data  = explode(",", $row);
          $hour  = $data[0];
          $min   = $data[1];
          $sec   = $data[2];
          $pow   = $data[3];
          $hourPuls[$hour] += $data[4];
          $minPuls[$hour][$min] += $data[4];
         
      }
      fclose($in);
   }
   $file = getFileName('hour',$year,$month,$day,'less');

   $out  = fopen($file,"w");
   if($out)
   {
      for($ii=0;$ii<24;$ii++)
      {
        $temp = $hourPuls[$ii];
        $content ="$ii,$temp\n";
        fwrite($out,$content,strlen($content)); 
      }
      fclose($out);
   }
   $file = getFileName('minute',$year,$month,$day,'less');

   $out  = fopen($file,"w");
   if($out)
   {
      for($ii=0;$ii<24;$ii++)
      {
        for($jj=0;$jj<60;$jj++)
        {
          $temp = $minPuls[$ii][$jj];
          $content ="$ii,$jj,$temp\n";
          fwrite($out,$content,strlen($content)); 
        }
      }
      fclose($out);
   }
}
//============================
function closeDataFiles() 
{
   global $limMonth,$g_log_rate;

   system("ls data/*.end > bess-end-list.txt");
   $in  = fopen("bess-end-list.txt","r");
   if($in)
   {
      while (!feof($in))
        {
          $file = trim(fgets($in));
          //echo("a1: $file<br>");
          // Year
          if(strstr($file,"year") != NULL)
          {
             $temp = str_replace(".end", "", $file);
             $year = str_replace("data/year-", "", $temp);

	     $value = 0;
             $maxValue = 0;
             for($ii=1;$ii<=12;$ii++)
             {
                $dataFile = getFileName("month",$year,$ii,"void","close");
                $res = readFileSum($dataFile);
		        $value += $res; 
                if($maxValue < $res)$maxValue = $res;
             }
             $dataFile = getFileName("year",$year,"void","void","close");
	         writeFile($dataFile,$value,$maxValue);
             $dataFile = getFileName("year",$year,"void","void","end");
             unlink($dataFile);            
          }
          // Month
          if(strstr($file,"month") != NULL)
          {
             $temp = str_replace(".end", "", $file);
             $temp = str_replace("data/month-", "", $temp);
             $time  = explode("-", $temp);
             $year  = $time[0];
             $month = $time[1];

	         $value = 0;
             $maxValue = 0;
             for($ii=1;$ii<=$limMonth[$month];$ii++)
             {
                $dataFile = getFileName("day",$year,$ii,"void","close");
		        $res = readFileSum($dataFile);
		        $value += $res; 
                if($maxValue < $res)$maxValue = $res;
             }
             $dataFile = getFileName("month",$year,$month,"void","close");
	         writeFile($dataFile,$value,$maxValue);
             $dataFile = getFileName("month",$year,$month,"void","end");
             unlink($dataFile);            
          }
          // Day
          if(strstr($file,"day") != NULL)
          {
             echo("a2: $file<br>");
             $temp = str_replace(".end", "", $file);
             $temp = str_replace("data/day-", "", $temp);
             $time  = explode("-", $temp);
             $year  = $time[0];
             $month = $time[1];
             $day   = $time[2];
             echo("Close: y=$year m=$month d=$day<br>");
             $kWh   = 0;
             $power = 0;
             $fitemp = getFileName("bess",$year,$month,$day,"txt");
             $in2  = fopen($fitemp,"r");
             if($in2)
             {
               $maxValue = 0;
               while (!feof($in2))
               {
                 $row    = fgets($in2);
                 $data   = explode(",", $row);
                 $kWh   += $data[4];
                 if($maxValue < $data[3])$maxValue = $data[3];
               }
               fclose($in2);
             }
             $power = round($power/3600);
             echo("Closing day: $day  Total kWh = $kWh ($power)<br>");
             echo("at: kWh=$kWh<br>");
             $dataFile = getFileName("day",$year,$month,$day,"close");
	         writeFile($dataFile,$kWh,$maxValue);
             $dataFile = getFileName("day",$year,$month,$day,"end");
             unlink($dataFile);            
          }
        }
       fclose($in);
 //echo("a5: ready<br>");
    }
}
//============================
function msTimeStamp() 
{
    return round(microtime(1) * 1000);
}
//============================
function checkWaveform($nsamples,$wave) 
{
    $sum = 0;
    for($ii=0;$ii<$nsamples;$ii++)
    {
      $sum = $sum + $wave[$ii];
    }
    $avg = $sum/$nsamples;
    return;
}
//============================
function updateAll() 
{
   system("ls data/bess-20*.txt > bess-day-list.txt");
   $in  = fopen("bess-day-list.txt","r");
   if($in)
   {
      while (!feof($in))
        {
          $file = trim(fgets($in));
          $temp2 = str_replace("bess-", "", $file);
          $temp2 = str_replace(".txt", "", $temp2);
          $temp2 = str_replace("data/", "", $temp2);
          $time  = explode("-", $temp2);
          $year  = $time[0];
          $month = $time[1];
          $day   = $time[2];
          $temp  = $year.'-'.$month.'-'.$day;
          sumDayLog($temp);
        }
       fclose($in);
    }
}
//============================
function setMin10($val,$min10)
{
  echo("<div id=lower align=left>");
  echo("<form action=\"bessvx.php\" method=\"POST\">");
  echo("<input name=\"f_event\"  type=\"hidden\" value=\"event_min10\"/>");
  echo("<select name=\"s_min10_$val\">");

  for($ii=0;$ii<6;$ii++)
  {
    $kk = $ii + 1;
    $temp = $ii*10;
    $selected = ' ';
    if($min10 == $ii)$selected = 'selected';
       echo("<option $selected value=\"$kk\">$temp</option>");
  }
  echo("</select>");

  echo("<input type=\"submit\" value=\"v&auml;lj 10 min intervall\" name=\"submit\">
  </form>");
  echo("</div>");
}

//============================
function setHour($val,$hour)
{
  echo("<div id=lower align=left>");
  echo("<form action=\"bessvx.php\" method=\"POST\">");
  echo("<input name=\"f_event\"  type=\"hidden\" value=\"event_hour\"/>");
  echo("<select name=\"s_hour$val\">");

  for($ii=0;$ii<24;$ii++)
  {
    $kk = $ii + 1;
    $selected = ' ';
    if($hour == $ii)$selected = 'selected';
       echo("<option $selected value=\"$kk\">$ii</option>");
  }
  echo("</select>");

  echo("<input type=\"submit\" value=\"v&auml;lj timme\" name=\"submit\">
  </form>");
  echo("</div>");
}
//============================
function setDay($val,$year,$month,$day)
{
  global $yearStart,$yearEnd,$nameMonth,$limMonth,$limYear;
  echo("<div id=lower align=left>");
  echo("<form action=\"bessvx.php\" method=\"POST\">");
  echo("<input name=\"f_event\"  type=\"hidden\" value=\"event_day\"/>");
  echo("<select name=\"s_year$val\">");
  for($ii=$yearStart;$ii<=$yearEnd;$ii++)
  {
    $selected = ' ';
    if($year == $ii)$selected = 'selected';
    echo("<option $selected value=\"$ii\">$ii</option>");
  }
  echo("</select>");
  echo("<select name=\"s_month$val\">");
  for($ii=1;$ii<=12;$ii++)
  {
    $selected = ' ';
    if($month == $ii)$selected = 'selected';
    echo("<option $selected value=\"$ii\">$nameMonth[$ii]</option>");
  }
  echo("</select>");

  echo("<select name=\"s_day$val\">");

  for($ii=1;$ii<=$limMonth[$month]+$limYear[$year][$month];$ii++)
  {
    $selected = ' ';
    if($day == $ii)$selected = 'selected';
       echo("<option $selected value=\"$ii\">$ii</option>");
  }
  echo("</select>");

  echo("<input type=\"submit\" value=\"v&auml;lj dag\" name=\"submit\">
  </form>");
  echo("</div>");
}
//============================
function setMonth($val,$year,$month)
{
  global $yearStart,$yearEnd,$nameMonth;
  echo("<div id=lower align=left>");
  echo("<form action=\"bessvx.php\" method=\"POST\">");
  echo("<input name=\"f_event\"  type=\"hidden\" value=\"event_month\"/>");
  echo("<select name=\"s_year$val\">");
  for($ii=$yearStart;$ii<=$yearEnd;$ii++)
  {
    $selected = ' ';
    if($year == $ii)$selected = 'selected';
    echo("<option $selected value=\"$ii\">$ii</option>");
  }
  echo("</select>");
  echo("<select name=\"s_month$val\">");
  for($ii=1;$ii<=12;$ii++)
  {
    $selected = ' ';
    if($month == $ii)$selected = 'selected';
    echo("<option $selected value=\"$ii\">$nameMonth[$ii]</option>");
  }
  echo("</select>");

  echo("<input type=\"submit\" value=\"v&auml;lj\" name=\"submit\">
  </form>");
  echo("</div>");
}
//============================
function setYear($val,$year)
{
  global $yearStart,$yearEnd;
  echo("<div id=lower align=left>");
  echo("<form action=\"bessvx.php\" method=\"POST\">");
  echo("<input name=\"f_event\"  type=\"hidden\" value=\"event_year\"/>");
  echo("<select name=\"s_year$val\">");
  for($ii=$yearStart;$ii<=$yearEnd;$ii++)
  {
    $selected = ' ';
    if($year == $ii)$selected = 'selected';
    echo("<option $selected value=\"$ii\">$ii</option>");
  }
  echo("</select>");

  echo("<input type=\"submit\" value=\"v&auml;lj\" name=\"submit\">
  </form>");
  echo("</div>");
}
//============================
function createPDE_single($file,$log,$conf)
{
global $g_bess_user,$g_log_rate,$g_pulse_rate;

$f = fopen($file,'w'); 

$c_scope  = $conf[scope];
$c_width  = $conf[width];
$c_height = $conf[height];
$c_scale  = $conf[scale];
$c_ymax   = $conf[ymax];
//$c_kwh    = $conf[kwh];
$c_hour   = $conf[hour];
$c_min10  = $conf[min10];
$c_filter = $conf[filter];

$content = "String[] lines;
int i,temp,maxVal=0,scaleVal;
int ot=0;int op=0;int floor=0;
int xstart;
int xend;

int maxValue()
{
  float power=0.,maxPower=0;
  int temp=0;
  lines = loadStrings(\"data/bess-$log.txt\");

  for(i=0;i<lines.length;i++)
  {
     String s2 = trim(lines[i]);
     String[] pieces = splitTokens(s2, \",\");
     if (pieces.length == 5) 
     {
       int h = int(pieces[0]);
       int m = int(pieces[1]);
       int s = int(pieces[2]);
       power = float(pieces[3]);
     }
     t = h*3600+m*60+s;
     if(t > xstart && t < xend)
     {
       if(maxPower < power)maxPower = power;
     }
  }
  for(i=0;i<100;i++)
  {
     if(maxPower > i*1000.0) temp = (i+1)*1000; 
  }
  return(temp);
}


int getScale(int value)
{
  int res = 50;
  if(value > 500)   res = 100;
  if(value > 1000)  res = 200;
  if(value > 2000)  res = 250;
  if(value > 4000)  res = 500;
  if(value > 10000) res = 1000;
  if(value > 20000) res = 2000;
  if(value > 50000) res = 10000;
  return(res);
}

void setup() {
  xstart = 0;
  xend   = 24*3600;
  size($c_width, $c_height);
  background(240);
  fill(255,0,0);
  text('$log',10,10);
  stroke(150,150,150);
  //line(0,$c_height-1,$c_width,$c_height-1);

  if('$c_scope' == 'day')
  {
   for(i=1;i<24;i++)
   {
    temp = i/24*$c_width;
    line(temp,$c_height,temp,15);
    text(i,temp,20);
   }
  }

  if('$c_scope' == 'hour')
  {
   text('Timme: $c_hour',200,10);
   xstart = $c_hour*3600;
   xend   = ($c_hour+1)*3600;
   for(i=1;i<60;i++)
   {
    temp = i/60*$c_width;
    line(temp,$c_height,temp,15);
    if(!(i%5))text(i,temp,20);
   }
  }

  if('$c_scope' == 'min10')
  {
   text('Timme: $c_hour Min10: $c_min10',200,10);
   xstart = $c_hour*3600 + $c_min10*600;
   xend   = $c_hour*3600 + ($c_min10+1)*600;
   for(i=1;i<7;i++)
   {
    temp = i/6*$c_width;
    line(temp,$c_height,temp,15);
    text(i*10,temp,20);
   }
  }

  maxVal = maxValue();
  scaleVal = getScale(maxVal);

  for(i=1;i<=int(maxVal/scaleVal);i++)
  {
    float yp = float(i*scaleVal)/(maxVal/$c_height);
    yp=$c_height-yp;
    line(0,yp,$c_width,yp);
    text(i*scaleVal,0,yp);
  }

  stroke(0,0,0);
  lines = loadStrings(\"data/bess-$log.txt\");
  int kwh = 0;
  int j,k,from,to;
  float[] phist = new float[100];
  float oldP=0,t,t_prev=0;

  for(i=0;i<=$c_filter;i++)phist[i] = 0.;
  for(i=0;i<lines.length;i++)
  {
     String s2 = trim(lines[i]);
     String[] pieces = splitTokens(s2, \",\");
     if (pieces.length == 7) 
     {
       int h = int(pieces[3]);
       int m = int(pieces[4]);
       int s = int(pieces[5]);
       phist[0] = float(pieces[6]);
       kwh++;
     }
     if (pieces.length == 8) 
     {
       int h = int(pieces[3]);
       int m = int(pieces[4]);
       int s = int(pieces[5]);
       phist[0] = float(pieces[6]);
       kwh +=  int(pieces[7]);
     }
     if (pieces.length == 5) 
     {
       int h = int(pieces[0]);
       int m = int(pieces[1]);
       int s = int(pieces[2]);
       phist[0] = float(pieces[3]);
       kwh +=  int(pieces[4]);
     }
     t_prev = t;
     t = h*3600+m*60+s;

     for(j=(int)t_prev;j<=(int)t;j++)
     {

       if(t > xstart && t < xend)
       {
        for(k=10;k>0;k--)phist[k] = phist[k-1];
        //phist[0] = float(pieces[6]);
        float sum = 0;
        for(k=0;k<$c_filter;k++)sum = sum + phist[k];
        oldP = p;
        float p = sum/$c_filter;  

        // presentation 
        float p1 = p/(maxVal/$c_height);    
        //println(t + ', ' + xstart + ', ' + xend + ', ' + p);
        //t = t/(24.0*3600.0)*$c_width;
        int temp = (j-xstart)/(xend - xstart)*$c_width;
        p1=$c_height-p1;
        int x = int(temp);
        int y = int(p1);
        line(ot,op,x,y);
        ot=x;op=y;
       }
     }
  }
  kwh = kwh/$g_pulse_rate;
  text(kwh+' kWh',100,10);
}


void draw() 
{
}

";
fwrite($f,$content,strlen($content)); 
fclose($f); 
}
//============================
function createPDE_less($file,$log,$conf)
{
global $g_bess_user,$g_log_rate,$g_pulse_rate;

$f = fopen($file,'w'); 

$c_scope  = $conf[scope];
$c_width  = $conf[width];
$c_height = $conf[height];
$c_scale  = $conf[scale];
$c_ymax   = $conf[ymax];
//$c_kwh    = $conf[kwh];
$c_hour   = $conf[hour];
$c_min10  = $conf[min10];
$c_filter = $conf[filter];
$c_typ    = $conf[typ];
$c_less   = $conf[less];

$content = "String[] lines;
int i,temp,maxVal=0,scaleVal;
int ot=0;int op=0;int floor=0;
int xstart;
int xend;

int maxValue()
{
  float power,maxPower=0;
  int temp;
  lines = loadStrings(\"data/min-$log.less\");

  for(i=0;i<lines.length;i++)
  {
     String s2 = trim(lines[i]);
     String[] pieces = splitTokens(s2, \",\");
     if (pieces.length == 3) 
     {
       int h = int(pieces[0]);
       int m = int(pieces[1]);
       int pp = int(pieces[2]);
     }
     t = h*60+m;
     if(t > xstart && t < xend)
     {
       if(maxPower < power)maxPower = power;
     }
  }
  for(i=0;i<50;i++)
  {
     if(maxPower > i*1000.0) temp = (i+1)*1000; 
  }
  return(temp);
}

int getScale(int value)
{
  if(value < 700)   return(50);
  if(value < 2000)  return(100);
  if(value < 4000)  return(200);
  if(value < 10000) return(500);
  if(value > 10000) return(1000);
}

void setup() {
  xstart = 0;
  xend   = 24*60;
  size($c_width, $c_height);
  background(240);
  fill(255,0,0);
  text('$log',10,10);
  stroke(150,150,150);
  //line(0,$c_height-1,$c_width,$c_height-1);

  if('$c_scope' == 'day')
  {
   for(i=1;i<24;i++)
   {
    temp = i/24*$c_width;
    line(temp,$c_height,temp,15);
    text(i,temp,20);
   }
  }

  }

  maxVal = maxValue();
  scaleVal = getScale(maxVal);

  for(i=1;i<=int(maxVal/scaleVal);i++)
  {
    float yp = float(i*scaleVal)/(maxVal/$c_height);
    yp=$c_height-yp;
    line(0,yp,$c_width,yp);
    text(i*scaleVal,0,yp);
  }

  stroke(0,0,0);
  lines = loadStrings(\"data/hour-$log.less\");
  int kwh = 0;
  int j,k,from,to;
  float[] phist = new float[100];
  float oldP=0,t,t_prev=0;

  for(i=0;i<=$c_filter;i++)phist[i] = 0.;
  for(i=0;i<lines.length;i++)
  {
     String s2 = trim(lines[i]);
     String[] pieces = splitTokens(s2, \",\");
     if (pieces.length == 3) 
     {
       int h  = int(pieces[0]);
       int m  = int(pieces[1]);
       int pp = int(pieces[2]);
       kwh += pp;
     }
     t_prev = t;
     t = h*60+m;

     for(j=(int)t_prev;j<=(int)t;j++)
     {

       if(t > xstart && t < xend)
       {
        // presentation 
        float p1 = pp/(maxVal/$c_height);    
        //println(t + ', ' + xstart + ', ' + xend + ', ' + p);
        //t = t/(24.0*60.0)*$c_width;
        int temp = (j-xstart)/(xend - xstart)*$c_width;
        p1=$c_height-p1;
        int x = int(temp);
        int y = int(p1);
        line(ot,op,x,y);
        ot=x;op=y;
       }
     }
  }
  kwh = kwh/$g_pulse_rate;
  text(kwh+' kWh',100,10);
}


void draw() 
{
}

";
fwrite($f,$content,strlen($content)); 
fclose($f); 
}
//============================
function createPDE_acc($file,$log1,$log2,$conf)
{
global $g_bess_user,$g_log_rate,$g_pulse_rate;
$f = fopen($file,'w'); 

$c_scope  = $conf[scope];
$c_width  = $conf[width];
$c_height = $conf[height];
$c_scale  = $conf[scale];
$c_ymax   = $conf[ymax];
//$c_kwh    = $conf[kwh];
$c_hour   = $conf[hour];
$c_filter = $conf[filter];

$content = "String[] lines;
int i,temp;
int ot=0;int op=0;int floor=0;
int xstart;
int xend;
void setup() {
  xstart = 0;
  xend   = 24*3600;
  size($c_width, $c_height);
  background(240);
  fill(255,0,0);
  text('$log1',10,10);
  stroke(150,150,150);
  //line(0,$c_height-1,$c_width,$c_height-1);

  if('$c_scope' == 'day')
  {
   for(i=1;i<24;i++)
   {
    temp = i/24*$c_width;
    line(temp,$c_height,temp,15);
    text(i,temp,20);
   }
  }

  if('$c_scope' == 'hour')
  {
   text('Timme: $c_hour',200,10);
   xstart = $c_hour*3600;
   xend   = ($c_hour+1)*3600;
   for(i=1;i<60;i++)
   {
    temp = i/60*$c_width;
    line(temp,$c_height,temp,15);
    if(!(i%5))text(i,temp,20);
   }
  }

  for(i=1;i<=int($c_ymax/$c_scale);i++)
  {
    float yp = float(i*$c_scale)/($c_ymax/$c_height);
    yp=$c_height-yp;
    line(0,yp,$c_width,yp);
    text(i*$c_scale,0,yp);
  }

  String s2;
  String[] pieces;
  int h,m,s,x,y,kwh;
  float p,a1,t1;
  float prev_t,t,acc;

  stroke(0,0,100);
  lines = loadStrings(\"data/bess-$log1.txt\");
  text(lines.length,200,40);
  kwh = 0;
  prev_t=0;
  t=0;
  acc=0;
  index = 0;
  for(i=0;i<lines.length;i++)
  {
     s2 = trim(lines[i]);
     pieces = splitTokens(s2, \",\");

     if (pieces.length == 7) 
     {
       int h = int(pieces[3]);
       int m = int(pieces[4]);
       int s = int(pieces[5]);
       p     = float(pieces[6]);
       kwh++;
     }
     if (pieces.length == 8) 
     {
       int h = int(pieces[3]);
       int m = int(pieces[4]);
       int s = int(pieces[5]);
       p     = float(pieces[6]);
       kwh  += int(pieces[7]);
     }
     if (pieces.length == 5) 
     {
       int h = int(pieces[0]);
       int m = int(pieces[1]);
       int s = int(pieces[2]);
       p     = float(pieces[3]);
       kwh +=  int(pieces[4]);
     }

       prev_t = t;
       t = h*3600+m*60+s;
       
       if(t > xstart && t < xend)
       {
        p = p*(t-prev_t)/3600;
        acc = acc + p;
        // adapt to window
        a1 =  acc/($c_ymax/$c_height);
        t1 = (t-xstart)/(xend - xstart)*$c_width;
        a1=$c_height-a1;
        x = int(t1);
        y = int(a1);
        line(ot,op,x,y);
        ot=x;op=y;
       }
  }
  kwh = kwh/$g_pulse_rate;
  text(kwh+' kWh',100,10);

// graph 2
  stroke(0,100,0);
  lines = loadStrings(\"data/bess-$log2.txt\");
  text(lines.length,100,40);
  kwh = 0;
  prev_t=0;
  t=0;
  acc=0;
  ot=0;op=0;
  for(i=0;i<lines.length;i++)
  {
     s2 = trim(lines[i]);
     pieces = splitTokens(s2, \",\");

     if (pieces.length == 7) 
     {
       int h = int(pieces[3]);
       int m = int(pieces[4]);
       int s = int(pieces[5]);
       p     = float(pieces[6]);
       kwh++;
     }
     if (pieces.length == 8) 
     {
       int h = int(pieces[3]);
       int m = int(pieces[4]);
       int s = int(pieces[5]);
       p     = float(pieces[6]);
       kwh  += int(pieces[7]);
     }
     if (pieces.length == 5) 
     {
       int h = int(pieces[0]);
       int m = int(pieces[1]);
       int s = int(pieces[2]);
       p     = float(pieces[3]);
       kwh +=  int(pieces[4]);
     }

       prev_t = t;
       t = h*3600+m*60+s;
       
       if(t > xstart && t < xend)
       {
        p = p*(t-prev_t)/3600;
        acc = acc + p;
        // adapt to window
        a1 =  acc/($c_ymax/$c_height);
        t1 = (t-xstart)/(xend - xstart)*$c_width;
        a1=$c_height-a1;
        x = int(t1);
        y = int(a1);
        line(ot,op,x,y);
        ot=x;op=y;
       }
  }
  text(' Acc ',10,10);
  kwh = kwh/$g_pulse_rate;
  text(kwh+' kWh',200,10);
}


void draw() 
{
}

";
fwrite($f,$content,strlen($content)); 
fclose($f); 
}
//============================
function createPDE_experiment($file,$log,$conf)
{

$f = fopen($file,'w'); 

$c_scope  = $conf[scope];
$c_width  = $conf[width];
$c_height = $conf[height];
$c_scale  = $conf[scale];
$c_ymax   = $conf[ymax];
$c_kwh    = $conf[kwh];

$content = "String[] lines;

void setup() {

  
}


void draw() 
{
}

";
fwrite($f,$content,strlen($content)); 
fclose($f); 
}
//============================
function createPDE_graphNow($file,$log,$conf)
{
$f = fopen($file,'w'); 

$c_scope  = $conf[scope];
$c_width  = $conf[width];
$c_height = $conf[height];
$c_scale  = $conf[scale];
$c_ymax   = $conf[ymax];
//$c_kwh    = $conf[kwh];
$c_hour   = $conf[hour];
$c_filter = $conf[filter];

$content = "String[] lines;
int i,j,temp=0,maxVal=0,scaleVal=0;
float ot=0,op=0;
int xstart,xend;
int h,m,s,t,old_t=0;
float x,y,p,ftemp;
int window = 200;
float center = $c_width;
int nbuff = 1000;
int[]   tBuff = new int[1001];
float[] pBuff = new float[1001];


int maxValue()
{
  float power=0.,maxPower=0.;
  int temp=0;

  for(i=nbuff;i>0;i--)
  {
     power = pBuff[i];
     if(maxPower < power)maxPower = power;
  }

  for(i=0;i<100;i++)
  {
     if(maxPower > i*1000.0) temp = (i+1)*1000; 
  }
  return(temp);
}

int getScale(int value)
{
  int res = 50;
  if(value > 500)   res = 100;
  if(value > 1000)  res = 200;
  if(value > 2000)  res = 250;
  if(value > 4000)  res = 500;
  if(value > 10000) res = 1000;
  if(value > 20000) res = 2000;
  if(value > 50000) res = 10000;
  return(res);
}


void setup() {
  size($c_width, $c_height);
  background(200);
  fill(255,0,0);
  stroke(150,150,150);
  lines = loadStrings(\"now.bess\");
  if(lines != null)
  {  
     h = int(lines[0]);
     m = int(lines[1]);
     s = int(lines[2]);
     p = float(lines[3]);
     t = h*3600+m*60+s;
  }

  xstart = t-window;
  xend   = t+window;
  for(i=0;i<=nbuff;i++)
  {
      tBuff[i] = 0;
      pBuff[i] = 0;
  }


}

float xx=1,yy=5;
void draw() 
{
  int tt;
  float pp;
  stroke(0,0,0);
  lines = loadStrings(\"now.bess\");
  if(lines != null)
  {  
    //String s2 = lines[0];
    //String[] pieces = splitTokens(s2, \",\");
    h = int(lines[0]);
    m = int(lines[1]);
    s = int(lines[2]);
    pp = float(lines[3]);
    tt = h*3600+m*60+s;
  } 
 
  xx++;if(xx>1000){xx=1;}
  point(xx,yy);

  if(old_t < tt)
  {

    for(i=nbuff;i>0;i--)
    {
      tBuff[i] = tBuff[i-1];
      pBuff[i] = pBuff[i-1];
    }
    tBuff[0] = tt;
    pBuff[0] = pp;
//=====================================
  background(200);
  fill(255,0,0);
  stroke(150,150,150);
  //  text(\"old_t=\",300,100);text(old_t,350,100);
  //  text(\"tt=\",400,100);text(tt,430,100);
  // presentation 

  maxVal   = maxValue();
  scaleVal = getScale(maxVal);

  p = pBuff[0]/(maxVal/$c_height);    
  //ftemp = (float)(center)/(xend - xstart)*$c_width;
  p = $c_height-p;
  ot = center;
  op = p;
  //point(x,y);

   for(i=0;i<window;i+=10)
   {
    ftemp = (float)i/window*$c_width;
    line(ftemp,$c_height,ftemp,15);
    if(i%50 == 0)text(i,ftemp,20);
   }

  for(i=1;i<=int(maxVal/scaleVal);i++)
  {
    float yp = float(i*scaleVal)/(maxVal/$c_height);
    yp=$c_height-yp;
    line(0,yp,$c_width,yp);
    text(i*scaleVal,0,yp);
  }
//====================================

   xx++;if(xx>1000){xx=1;}
   point(xx,yy+10);

    stroke(0,0,0);
    for(i=1;i<=nbuff;i++)
    {
     // text(i,200,200);
      p = pBuff[i]; 
      int time = tBuff[0] - tBuff[i];

      if(p > 0.0 && time <= center)
      {

      // presentation 
 
      ftemp = (float)time/(xend - xstart)*$c_width;
      x = center-ftemp;

      ftemp = p/(maxVal/$c_height);   
      y = $c_height-ftemp;

      line(ot,op,x,y);
      ot=x;op=y;
      }
    }
  }
  old_t = tt;
}

";
fwrite($f,$content,strlen($content)); 
fclose($f); 
}
//============================
function createPDE_year($file,$year,$conf)
{
  global $yearStart,$yearEnd,$distMonth;

  $f = fopen("year.bess",'w'); 
  $maxp = 0;
  $sum = 0;
  for($ii=1;$ii<=12;$ii++)
  {
    $fitemp = getFileName('month',$year,$ii,'void','close'); 
    $temp = readFileSum($fitemp);
    $sum = $sum +$temp;
    if($maxp < $temp)$maxp = $temp;
    fwrite($f,"$ii,$temp\n");
  }
  //$maxp =$maxp/1000.;
  //$sum = $sum /1000.;
  fclose($f);


$f = fopen($file,'w'); 

$c_scope  = $conf[scope];
$c_width  = 600; //$conf[width];
$c_height = 300; //$conf[height];
$c_scale  = 50; //$conf[scale];
$c_ymax   = $maxp+50; //$conf[ymax];
$c_kwh    = $conf[kwh];
$c_hour   = $conf[hour];

$content = "String[] lines;
int i,temp;
int ot=0;int op=0;int floor=0;
int xstart;
int xend;
void setup() 
{
  size($c_width, $c_height);
  background(240);
  fill(255,0,0);
  text('$year',10,10);
  temp = round($sum);
  text(temp+' kWh',100,10);
  stroke(150,150,150);
  //line(0,$c_height-1,$c_width,$c_height-1);

   for(i=1;i<=12;i++)
   {
    temp = i/13*$c_width;
    line(temp,$c_height,temp,15);
    text(i,temp+10,20);
   }

  for(i=1;i<=int($c_ymax/$c_scale);i++)
  {
    float yp = float(i*$c_scale)/($c_ymax/$c_height);
    yp=$c_height-yp;
    line(0,yp,$c_width,yp);
    text(i*$c_scale,0,yp);
  }

  stroke(0,0,0);
  lines = loadStrings(\"year.bess\");
  for(i=0;i<lines.length;i++)
  {
     String s2 = trim(lines[i]);
     String[] pieces = splitTokens(s2, \",\");
     if (pieces.length == 2)
     {
       float x = float(pieces[0]);
       float y = float(pieces[1]);
       float z = 1./13.*$c_width;
       int yx = y/$c_ymax*$c_height;
       x = x*z;
       fill(102);
       rect(x,$c_height,z,-yx);
       fill(0);
       if(yx > 0)
       {
         y = round(y);
         text(y,x,$c_height-10);
       }
   }
  }
}


void draw() 
{
}

";
fwrite($f,$content,strlen($content)); 
fclose($f); 
}
//============================
function createPDE_month($file,$year,$month,$conf)
{
  global $yearStart,$yearEnd,$distDay,$limMonth;
  $f = fopen("month.bess",'w'); 
  $maxp  = 0;
  $ndays = $limMonth[$month];
  $sum   = 0;
  for($ii=1;$ii<=$ndays;$ii++)
  {
    $fitemp = getFileName('day',$year,$month,$ii,'close'); 
    $temp   = readFileSum($fitemp);
    $sum    = $sum +$temp;
    if($maxp <$temp)$maxp = $temp;
    fwrite($f,"$ii,$temp\n");
  }
  //$maxp =$maxp/1000.;
  //$sum = $sum /1000.;
  fclose($f);

$f = fopen($file,'w'); 

$c_scope  = $conf[scope];
$c_width  = 600; //$conf[width];
$c_height = 300; //$conf[height];
$c_scale  = 5; //$conf[scale];
$c_ymax   = $maxp+5; //$conf[ymax];
$c_kwh    = $conf[kwh];
$c_hour   = $conf[hour];

$content = "String[] lines;
int i,temp;
float ftemp;
int ot=0;int op=0;int floor=0;
int xstart;
int xend;
void setup() 
{
  size($c_width, $c_height);
  background(240);
  fill(255,0,0);
  text('$year $month',10,10);
  ftemp = $sum;
  text(ftemp+' kWh',100,10);
  stroke(150,150,150);
  //line(0,$c_height-1,$c_width,$c_height-1);

   for(i=1;i<=$ndays;i++)
   {
    temp = i/($ndays+1)*$c_width;
    line(temp,$c_height,temp,15);
    text(i,temp+3,20);
   }

  for(i=1;i<=int($c_ymax/$c_scale);i++)
  {
    float yp = float(i*$c_scale)/($c_ymax/$c_height);
    yp=$c_height-yp;
    line(0,yp,$c_width,yp);
    text(i*$c_scale,0,yp);
  }

  stroke(0,0,0);
  lines = loadStrings(\"month.bess\");
  for(i=0;i<lines.length;i++)
  {
     String s2 = trim(lines[i]);
     String[] pieces = splitTokens(s2, \",\");
     if (pieces.length == 2)
     {
       float x = float(pieces[0]);
       float y = float(pieces[1]);
       float z = 1./($ndays+1)*$c_width;
       int yx = y/$c_ymax*$c_height;
       x = x*z;
       fill(102);
       rect(x,$c_height,z,-yx);
       fill(0);
       if(yx > 0)
       {
          y = round(y);
          text(y,x,$c_height-10);
       }
   }
  }
}


void draw() 
{
}

";
fwrite($f,$content,strlen($content)); 
fclose($f); 
}
//============================
function createPDE_lessHour($file,$log,$conf)
{
global $g_pulse_rate;

$f = fopen($file,'w'); 

$c_scope  = $conf[scope];
$c_width  = 1000; //$conf[width];
$c_height = 300; //$conf[height];
$c_scale  = 100; //$conf[scale];
$c_ymax   = 1000+5; //$conf[ymax];
//$c_kwh    = $conf[kwh];
$c_hour   = $conf[hour];

$content = "String[] lines;
int i,temp;
float ftemp;
int ot=0;int op=0;int floor=0;
int xstart;
int xend;
int kwh=0;

int maxValue()
{
  float power=0.,maxPower=0;
  int temp=0;
  lines = loadStrings(\"$log\");

  for(i=0;i<lines.length;i++)
  {
     String s2 = trim(lines[i]);
     String[] pieces = splitTokens(s2, \",\");
     if (pieces.length == 2) 
     {
       int h = int(pieces[0]);
       power = float(pieces[1]);
     }
     if(maxPower < power)maxPower = power;
     kwh += power;
  }
  maxPower = maxPower*1000./$g_pulse_rate*3600/3600; //Average Watt during hour
  for(i=0;i<50;i++)
  {
     if(maxPower > i*1000.0) temp = (i+1)*1000; 
  }
  return(temp);
}

int getScale(int value)
{
  int res = 50;
  if(value > 500)   res = 100;
  if(value > 1000)  res = 200;
  if(value > 2000)  res = 250;
  if(value > 4000)  res = 500;
  if(value > 10000) res = 1000;
  if(value > 20000) res = 2000;
  if(value > 20000) res = 10000;
  return(res);
}


void setup() 
{
  size($c_width, $c_height);
  background(240);
  fill(255,0,0);
  stroke(150,150,150);
  line(0,$c_height-1,$c_width,$c_height-1);

   for(i=0;i<24;i++)
   {
    temp = i/24*$c_width;
    line(temp,$c_height,temp,15);
    text(i,temp+3,20);
   }
   
  int maxVal   = maxValue();         //c_ymax
  int scaleVal = getScale(maxVal); //c_scale

  for(i=1;i<=int(maxVal/scaleVal);i++)
  {
    float yp = float(i*scaleVal)/(maxVal/$c_height);
    yp=$c_height-yp;
    line(0,yp,$c_width,yp);
    text(i*scaleVal,0,yp);
  }

  stroke(0,0,0);
  lines = loadStrings(\"$log\");
  for(i=0;i<lines.length;i++)
  {
     String s2 = trim(lines[i]);
     String[] pieces = splitTokens(s2, \",\");
     if (pieces.length == 2)
     {
       float x = float(pieces[0]);
       float y = float(pieces[1])*1000/$g_pulse_rate*3600/3600; // Average Watt during hour
       // presentation
       float z = 1./24*$c_width;
       float yx = y/maxVal*$c_height;
       x = x*z;
       fill(102);
       rect(x,$c_height,z,-yx);
       fill(0);
   }
  }
  kwh = kwh/$g_pulse_rate;
  text(kwh+' kWh',100,10);
}


void draw() 
{
}

";
fwrite($f,$content,strlen($content)); 
fclose($f); 
}

//============================
function createPDE_lessMinute($file,$log,$conf)
{
global $g_pulse_rate;

$f = fopen($file,'w'); 

$c_scope  = $conf[scope];
$c_width  = $conf[width];
$c_height = $conf[height];
$c_scale  = $conf[scale];
$c_ymax   = $conf[ymax];
$c_kwh    = $conf[kwh];
$c_hour   = $conf[hour];

$content = "String[] lines;
int i,temp;
float ftemp;
int ot=0;int op=0;int floor=0;
int xstart;
int xend;
int kwh=0;

int maxValue()
{
  float power=0.,maxPower=0.;
  int temp=0;
  lines = loadStrings(\"$log\");

  for(i=0;i<lines.length;i++)
  {
     String s2 = trim(lines[i]);
     String[] pieces = splitTokens(s2, \",\");
     if (pieces.length == 3) 
     {
       int h = int(pieces[0]);
       int m = int(pieces[1]);
       power = float(pieces[2]);
     }
     if(maxPower < power)maxPower = power;
     kwh += power;
  }
  maxPower = maxPower*1000/$g_pulse_rate*3600/60; //Average Watt during minute
  for(i=0;i<100;i++)
  {
     if(maxPower > i*1000.0) temp = (i+1)*1000; 
  }
  return(temp);
}

int getScale(int value)
{
  int res = 50;
  if(value > 500)   res = 100;
  if(value > 1000)  res = 200;
  if(value > 2000)  res = 250;
  if(value > 4000)  res = 500;
  if(value > 10000) res = 1000;
  if(value > 20000) res = 2000;
  if(value > 50000) res = 10000;
  return(res);
}


void setup() 
{
  size($c_width, $c_height);
  background(240);
  fill(255,0,0);
  stroke(150,150,150);
  line(0,$c_height-1,$c_width,$c_height-1);

   for(i=0;i<24;i++)
   {
    temp = i/24*$c_width;
    line(temp,$c_height,temp,15);
    text(i,temp+3,20);
   }

  int maxVal   = maxValue();         //c_ymax
  int scaleVal = getScale(maxVal); //c_scale

  for(i=1;i<=int(maxVal/scaleVal);i++)
  {
    float yp = float(i*scaleVal)/(maxVal/$c_height);
    yp=$c_height-yp;
    line(0,yp,$c_width,yp);
    text(i*scaleVal,0,yp);
  }

  stroke(0,0,0);
  lines = loadStrings(\"$log\");
  for(i=0;i<lines.length;i++)
  {
     String s2 = trim(lines[i]);
     String[] pieces = splitTokens(s2, \",\");
     if (pieces.length == 3)
     {
       float h = float(pieces[0]);
       float m = float(pieces[1]);
       float x = h*60 + m;
       float y = float(pieces[2])*1000/$g_pulse_rate*3600/60; //Average Watt during minute
       // presentation
       float z = 1./24/60*$c_width;
       float yx = $c_height - y/maxVal*$c_height;
       x = x*z;
       line(ot,op,x,yx);
       ot=x;op=yx;
   }
  }
  kwh = kwh/$g_pulse_rate;
  text(kwh+' kWh',100,10);
}


void draw() 
{
}

";
fwrite($f,$content,strlen($content)); 
fclose($f); 
}
//=======================================
function getExtension($str)
//======================================= 
{
  $i = strrpos($str,".");
  if (!$i) { return ""; }
  $l = strlen($str) - $i;
  $ext = substr($str,$i+1,$l);
  return $ext;
}

//=======================================
function safeText($text)
//=======================================
{
   $text = str_replace("#", "No.", $text); 
   $text = str_replace("$", "Dollar", $text); 
   $text = str_replace("%", "Percent", $text); 
   $text = str_replace("^", "", $text); 
   $text = str_replace("&", "and", $text); 
   $text = str_replace("*", "", $text); 
   $text = str_replace("?", "", $text); 
   return($text);
}
//=======================================
function uploadFile()
//=======================================
{
  define ("MAX_SIZE","90000");
  $errors=0;
  $newname = '';

  if(isset($_POST['submit_file']))
    {
     if ($_FILES['import_file']['error'] > 0)
     {
       echo "Return Code: " . $_FILES['import_file']['error'] . "<br>";
       echo(" Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.<br>");
     }

      $import=$_FILES['import_file']['name'];
      if ($import)
        {
          $file_name = stripslashes($_FILES['import_file']['name']);
          $file_name = safeText($file_name);
          $extension = getExtension($file_name);
          $extension = strtolower($extension);
          if ($extension != "zip")
            {
              echo "<h1>Unknown Import file Extension: $extension</h1>";
              $errors=1;
            }
          else
            {
              $size=filesize($_FILES['import_file']['tmp_name']);
              if ($size > MAX_SIZE*1024)
                {
                  echo "<h1>You have exceeded the size limit! $size</h1>";
                  $errors=1;
                }
              $newname='import.zip';
              //$copied = move_uploaded_file($_FILES['import_file']['tmp_name'], $newname);
              $copied = copy($_FILES['import_file']['tmp_name'], $newname);
              if (!$copied)
                {
                  echo "<h1>Import failed! $size</h1>";
                  $errors=1;
                }
            }
        }
    }

  if(isset($_POST['submit_file']) && !$errors)
    {
      chmod($newname,0666);
      echo "<h1>File Uploaded Successfully! Size=$size</h1>";
      //system("rm -r data; unzip $newname;");
      system("unzip $newname;");
    }
  return($newname);
}
//============= END LIBRARY ===============
?>
